/**to load system & application function from xml
 * this class implements tech of plugin
 * by fuzhou huilin corp.ltd @author lms 2016.08.23
 */
package com.fzrskj.cloud.free.core.tool;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

public class CXmlFunParser {
	//private declarations
	private static HashMap<String, CApi> sysFuns;
	private static HashMap<String, CApi> appFuns;

	//to initialize global function configulation object
	static{
		sysFuns = new HashMap<String, CApi>();
		appFuns = new HashMap<String, CApi>();
		CXmlFunParser xmlParser = new CXmlFunParser();
		xmlParser.parserXml("/config/sysApi.xml", sysFuns);
		xmlParser.parserXml("/config/appApi.xml", appFuns);
	}

	private void parserXml(String fileName, HashMap<String, CApi> funs){
		try{
			InputStream in = this.getClass().getResourceAsStream(fileName);
			SAXReader reader = new SAXReader();
			Document doc = reader.read(in);
			Element root = doc.getRootElement();
			List<Element> items = root.elements();
			for(Element fun : items){
				CApi api = new CApi();
				api.setDescription(fun.attributeValue("desc"));
				api.setApiName(fun.attributeValue("apiName"));
				api.setClassName(fun.attributeValue("className"));
				api.setFunctionName(fun.attributeValue("function"));
				api.setFunctionCode(fun.attributeValue("funId"));
				api.setCloudLogin(fun.attributeValue("cloudLogin"));
				api.setMiniServer(fun.attributeValue("miniServer"));
				funs.put(api.getApiName(), api);
			}
			in.close();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
	
	/**to get api object by apiName
	 * @param type 0-framework api; 1-business system api
	 * @param apiName api name
	 * @return if api exists, return Api object, otherwise return null
	 * @author lms 2016.08.25
	 */
	public static CApi getApi(int type, String apiName){
		if (type==0) {
			return sysFuns.get(apiName);
		}

		return appFuns.get(apiName);
	}

}
